import 'dart:collection';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_play_time_page.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

/// 设置播放周期弹窗
class SetPlayIntervalDialog extends StatefulWidget {

  static const String RESULT_START_DAY_STR = "result_start_day_str";
  static const String RESULT_END_DAY_STR = "result_end_day_str";
  static const String SHOW_TERMINAL_ARRANGE = "show_terminal_arrange";

  final String title;
  
  final String backup;

  final String cancelText;

  final String confirmText;

  final Color confirmBgColor;

  final VoidCallback onConfirm;

  final VoidCallback onPop;
  
  final DateTime startDay;
  
  final DateTime endDay;
  
  final bool showTerminalRange;

  const SetPlayIntervalDialog(this.title, this.startDay,this.endDay, {Key key, 
    this.backup, 
     this.cancelText, this.confirmText, this.confirmBgColor, 
    this.onConfirm, this.onPop, this.showTerminalRange
  }) : super(key: key);

  static Future<Map<String, dynamic>> navigatorPushDialog(BuildContext context,
      String title, DateTime startDay, DateTime endDay,
      {String backup, String cancelText, String confirmText, Color confirmBgColor,
        bool showTerminalRange, VoidCallback onPop, VoidCallback onConfirm,
      }){
    return VgDialogUtils.showCommonDialog<Map<String, dynamic>>(context: context, child: SetPlayIntervalDialog(
      title, startDay, endDay,
      backup: backup,
      cancelText: cancelText,
      confirmText: confirmText,
      confirmBgColor: confirmBgColor,
      showTerminalRange: showTerminalRange,
      onPop: onPop,
      onConfirm: onConfirm,
    ),barrierDismissible: false);
  }

  @override
  _SetPlayIntervalDialogState createState() => _SetPlayIntervalDialogState();

}

class _SetPlayIntervalDialogState extends BaseState<SetPlayIntervalDialog>{
  bool _currentTerminal = true;
  DateTime _startDay;
  DateTime _endDay;
  String _endDayStr;
  int _selectIndex = 1;

  int _interval = 15;
  @override
  void initState() {
    super.initState();
    _startDay = widget?.startDay;
    _endDay = widget?.endDay;
    DateTime currentDay = DateTime.now();
    if(_startDay != null && _endDay != null){
      if(currentDay.millisecondsSinceEpoch > _startDay.millisecondsSinceEpoch){
        _interval = (((_endDay.millisecondsSinceEpoch - currentDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1);
      }else{
        _interval = (((_endDay.millisecondsSinceEpoch - _startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1);
      }

    }
    print("interval：" + _interval.toString());
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: ()=> RouterUtils.pop(context),
      child: UnconstrainedBox(
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){},
          child: Material(
            type: MaterialType.transparency,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Container(
                width: 290,
                decoration: BoxDecoration(
                    color: ThemeRepository.getInstance().getCardBgColor_21263C()
                ),
                child: _toMainColumnWidget(context),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _toMainColumnWidget(BuildContext context){
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        SizedBox(height: 25,),
        Text(
          widget?.title ?? "提示",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
              fontSize: 16,
              fontWeight: FontWeight.w600
          ),
        ),
        SizedBox(height: 20,),
        _toTimeWidget(),
        _toBackUpWidget(),
        _toTerminalRangeWidget(),
        SizedBox(height: 25,),
        _toTwoButtonWidget(context),
      ],
    );
  }

  ///日期选择
  Widget _toTimeWidget(){
    _endDayStr = DateUtil.getDateStrByDateTime(_endDay, format: DateFormat.YEAR_MONTH_DAY);
    String foreverStr = DateUtil.getDateStrByDateTime(DateTime.parse("9999-99-99"), format: DateFormat.YEAR_MONTH_DAY);
    if(foreverStr == _endDayStr){
      _endDayStr = "永久";
    }else{
      _endDayStr = DateUtil.getDateStrByDateTime(_endDay, format: DateFormat.ZH_MONTH_DAY);
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: Container(
        width: 230,
        height: 45,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            color: ThemeRepository.getInstance().getBgOrSplitColor_191E31()
        ),
        child: Row(
          children: [
            GestureDetector(
              onTap: () {
                setState(() {
                  _selectIndex = 1;
                });
                _startDatePicker();
              },
              child: Row(
                children: [
                  Container(
                    width: 86,
                    alignment: Alignment.center,
                    child: Text(
                      "${DateUtil.getDateStrByDateTime(_startDay, format: DateFormat.ZH_MONTH_DAY)}",
                      style: TextStyle(
                          color: (_selectIndex == 1)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                          ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(right: 10),
                    child: Image.asset(
                      "images/icon_arrow_down.png",
                      width: 12,
                    ),
                  ),
                ],
              ),
            ),
            Text(
              "至",
              style: TextStyle(
                color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                fontSize: 14,
              ),
            ),
            GestureDetector(
              onTap: (){
                setState(() {
                  _selectIndex = 2;
                });
                _endDatePicker();
              },
              child: Row(
                children: [
                  Container(
                    width: 86,
                    alignment: Alignment.center,
                    child: Text(
                      _endDayStr,
                      style: TextStyle(
                          color: (_selectIndex == 2)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                          ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(right: 10),
                    child: Image.asset(
                      "images/icon_arrow_down.png",
                      width: 12,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _startDatePicker(){
    return DatePicker.showDatePicker(
        context,
        pickerTheme: DateTimePickerTheme(
            showTitle: true,
            backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            confirm: Text('确定',
                style: TextStyle(
                  color:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                )),
            cancel: Text('取消',
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
            itemTextStyle: TextStyle(color: Colors.white)
          // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        ),
        minDateTime: DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY)), //起始日期
        maxDateTime: getMaxEndDay(), //终止日期
        initialDateTime: _startDay, //当前日期
        dateFormat: 'yyyy-MMMM-dd',  //显示
        locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us// 格式
        onClose: () => print("----- onClose -----"),
        onCancel: () => print('onCancel'),
        onConfirm: (dateTime, List<int> index) { //确定的时候
          _startDay = dateTime;
          if(_endDay.millisecondsSinceEpoch < dateTime.millisecondsSinceEpoch){
            int milliseconds = _startDay.millisecondsSinceEpoch + (1000*3600*24)*_interval;
            DateTime tempDate = DateTime.parse(DateUtil.formatDateMs(milliseconds));
            _endDay = tempDate;
          }
          setState(() {

          });
        }
    );
  }

  _endDatePicker(){
    return DatePicker.showDatePicker(
        context,
        pickerTheme: DateTimePickerTheme(
            showTitle: true,
            backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            confirm: Text('确定',
                style: TextStyle(
                  color:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                )),
            cancel: Text('取消',
                style: TextStyle(
                    color:
                    ThemeRepository.getInstance().getTextBFC2CC_BFC2CC())),
            itemTextStyle: TextStyle(color: Colors.white)
          // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        ),
        minDateTime: getMinStartDay(), //起始日期
        maxDateTime: getMaxEndDay(), //终止日期
        initialDateTime: _endDay, //当前日期
        dateFormat: 'yyyy-MMMM-dd',  //显示
        locale: DateTimePickerLocale.zh_cn, //语言 默认DateTimePickerLocale.en_us// 格式
        onClose: () => print("----- onClose -----"),
        onCancel: () => print('onCancel'),
        onConfirm: (dateTime, List<int> index) { //确定的时候
          if(dateTime.millisecondsSinceEpoch < _startDay.millisecondsSinceEpoch){
            VgToastUtils.toast(context, "结束日期不能早于开始日期");
            return;
          }
          setState(() {
            _endDay = dateTime;
          });
        }
    );
  }

  DateTime getMinStartDay(){
    DateTime currentDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
    if(currentDay.millisecondsSinceEpoch > _startDay.millisecondsSinceEpoch){
      return DateTime.parse(DateUtil.getDateStrByDateTime(currentDay, format: DateFormat.YEAR_MONTH_DAY));
    }
    return DateTime.parse(DateUtil.getDateStrByDateTime(_startDay, format: DateFormat.YEAR_MONTH_DAY));
  }

  DateTime getMaxEndDay(){
    //yyyy-MM-dd
    String startDayStr = DateUtil.getDateStrByDateTime(_startDay, format: DateFormat.YEAR_MONTH_DAY);
    int maxEndYear = int.parse(startDayStr.substring(0, 4)) + 10;
    String maxEndDayStr = maxEndYear.toString() + startDayStr.substring(4, startDayStr.length);
    return DateTime.parse(maxEndDayStr);
  }

  ///备注
  Widget _toBackUpWidget(){
    return Visibility(
      visible: StringUtils.isNotEmpty(widget?.backup??""),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 30),
        margin: EdgeInsets.only(top: 12),
        child: RichTextWidget(
          overFlow: TextOverflow.visible,
          fontSize: 14,
          height: 1.2,
          contentMap: LinkedHashMap.from({
          '注：':ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
          '${widget?.backup??"设置后将应用于全部显示屏"}':ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
        }),),
      ),
    );
  }

  ///设置终端范围
  Widget _toTerminalRangeWidget(){
    return Visibility(
      visible: widget?.showTerminalRange??false,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 20,),
            GestureDetector(
              onTap: (){
                setState(() {
                  _currentTerminal = true;
                });
              },
              child: Row(
                children: <Widget>[
                  AnimatedSwitcher(
                    duration: DEFAULT_ANIM_DURATION,
                    child: Image.asset(
                      _currentTerminal
                          ?"images/icon_terminal_select.png"
                          :"images/icon_terminal_unselect.png",
                      width: 20,
                      height: 20,
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text(
                    "仅应用于当前显示屏",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextMainColor_D0E0F7(),
                        fontSize: 14,
                        height: 1.2),
                  ),
                ],
              ),
            ),
            SizedBox(height: 20,),
            GestureDetector(
              onTap: (){
                setState(() {
                  _currentTerminal = false;
                });
              },
              child: Row(
                children: <Widget>[
                  AnimatedSwitcher(
                    duration: DEFAULT_ANIM_DURATION,
                    child: Image.asset(
                      _currentTerminal
                          ?"images/icon_terminal_unselect.png"
                          :"images/icon_terminal_select.png",
                      width: 20,
                      height: 20,
                    ),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text(
                    "应用于全部显示屏",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextMainColor_D0E0F7(),
                        fontSize: 14,
                        height: 1.2),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///取消确定
  Widget _toTwoButtonWidget(BuildContext context){
    return Container(
      height: 40,
      child: Row(
        children: <Widget>[
            Expanded(
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: (){
                  if(widget?.onPop != null){
                    widget?.onPop?.call();
                    return ;
                  }
                  RouterUtils.pop(context);
                },
                child: Container(
                  color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
                  child: Center(
                    child:  Text(
                      widget?.cancelText ?? "取消",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: VgColors.INPUT_BG_COLOR,
                          fontSize: 14,
                          height: 1.2
                      ),
                    ),
                  ),
                ),
              ),
            ),
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: (){
                if(widget?.onConfirm != null){
                  widget?.onConfirm?.call();
                }
                RouterUtils.pop(context, result: {
                SetPlayIntervalDialog.RESULT_START_DAY_STR: DateUtil.getDateStrByDateTime(_startDay, format: DateFormat.YEAR_MONTH_DAY),
                SetPlayIntervalDialog.RESULT_END_DAY_STR: ("永久" == _endDayStr)?"9999-99-99": DateUtil.getDateStrByDateTime(_endDay, format: DateFormat.YEAR_MONTH_DAY),
                SetPlayIntervalDialog.SHOW_TERMINAL_ARRANGE: (_currentTerminal??true)?"01":"00",
                });
              },
              child: Container(
                color:widget?.confirmBgColor?? ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                child: Center(
                  child:  Text(
                    widget?.confirmText ?? "确定",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        height: 1.2
                    ),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

}
